// pages/confirmOrder/confirmOrder.js
const app = getApp()
let request = require('../../utils/request.js')
let addFlag = false

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: app.globalData.screenHeight,
    agreementShow: false,
    carNumList: [],
    checkCarIndex: 0,
    inputLen: 8,
    activeIptIndex: -1,
    carNo: '',
    addCarDialog: false,
    couponDialog: false,
    couponList: [],
    couponIndex: -1,
    checkedCouopn: {},
    totalPrices: 0,
    subtract: 0,
    renewType: '',
    parkName: '',
    parkId: 0,
    orderData: {},
    monthlyList: [{
      monthRentName: '月卡',
      sumAmount: 189,
      days: 30
    },
    {
      monthRentName: '季卡',
      sumAmount: 189,
      days: 90
    },
    {
      monthRentName: '年卡',
      sumAmount: 189,
      days: 365
    }
    ],
    monthlyIndex: 0,
    durationList: [{
      time: '100',
      money: '40',
      average: 1.2
    },
    {
      time: '100',
      money: '40',
      average: 1.2
    },
    {
      time: '100',
      money: '40',
      average: 1.2
    }
    ],
    durationIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('会员卡信息：', options)
    this.setData({
      renewType: options.type,
      parkId: options.parkId,
      parkName: options.parkName,
      carName: options.carName,
      cardType: options.cardType
    })
    // let data = JSON.parse(options.payData)
    // this.setData({
    //   orderData: data
    // })
    // if (data.type == 'MONTH') {
    //   this.getCarNumList()
    // } else if (data.type == 'DURATION') {

    // } else if (data.type == 'CUSTOMIZE') {
    // }
    this.getCarNumList()
    this.getMonthRule()
  },
  /**
   * 选择月卡
   * @param {*} e 
   */
  selectMonthly(e) {
    let index = e.currentTarget.dataset.index
    if (index == this.data.monthlyIndex) {
      return
    }
    this.setData({
      monthlyIndex: index,
      "orderData.paidAmount": this.data.monthlyList[index].sumAmount,
      'orderData.monthRuleId': this.data.monthlyList[index].monthRuleId,
      'orderData.monthRentType': this.data.monthlyList[index].monthRentType,
      'orderData.uniformRentType': this.data.monthlyList[index].uniformRentType,
      totalPrices: 0,
      checkedCouopn: {},
      couponIndex: -1,
      subtract: 0
    })
    this.getCoupon()
  },
  selectDuration(e) {
    let index = e.currentTarget.dataset.index
    if (index == this.data.durationIndex) {
      return
    }
    this.setData({
      durationIndex: index
    })
  },
  /**
   * 获取月租规则
   */
  getMonthRule() {
    let that = this
    let url = '/promotion/month-rule-paytype/getMonthRulePaytypeByParkId'
    let parmas = {
      parkId: this.data.parkId,
      cardType: this.data.cardType
    }
    console.log('data参数：', this.data)
    request.http(url, 'GET', parmas)
      .then(res => {
        console.log('月租规则：', res.data)
        let data = res.data
        if (data.code == 200) {
          if (typeof (data.data) == 'string') {
            that.setData({
              monthlyList: [],
            })
          } else {
            that.setData({
              monthlyList: data.data,
              renewMoney: data.data[0].sumAmount,
              'orderData.paidAmount': data.data[0].sumAmount,
              'orderData.monthRuleId': data.data[0].monthRuleId,
              'orderData.monthRentType': data.data[0].monthRentType,
              'orderData.uniformRentType': data.data[0].uniformRentType              
            })
            that.getCoupon()
          }
        }
      })
  },
  /**
   * 查询优惠券
   */
  getCoupon() {
    let that = this
    let url = '/customer/ticket/getNotExpiredValidTicket'
    let parmas = {
      cardType: 3,
      amount: this.data.orderData.paidAmount
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let coupon = data.data
          for (var i = 0; i < coupon.length; i++) {
            coupon[i].checked = false
          }
          that.setData({
            couponList: coupon
          })
        }
      })
  },
  /**
   * 选择优惠券
   * @param {*} e 
   */
  getDiscount(e) {
    let index = e.currentTarget.dataset.index
    let couponIndex = this.data.couponIndex
    let coupon = this.data.couponList
    if (index == couponIndex) {
      coupon[index].checked = false
      this.setData({
        checkedCouopn: {},
        couponIndex: -1,
        subtract: 0
      })
    } else {
      for (var i = 0; i < coupon.length; i++) {
        if (index == i) {
          coupon[i].checked = true
        } else {
          coupon[i].checked = false
        }
      }
      this.setData({
        checkedCouopn: coupon[index],
        couponIndex: index
      })
    }
    this.setData({
      couponList: coupon
    })
    if (this.data.checkedCouopn.ticketId) {
      this.countCoupon()
    }
    this.hideCouponDialog()
  },
  /**
   * 计算优惠价格
   */
  countCoupon() {
    let that = this
    let url = '/customer/ticket/getDiscountAmontWithTicket'
    let parmas = {
      paidAmount: this.data.orderData.paidAmount,
      receivableAmount: this.data.orderData.paidAmount,
      ticketId: this.data.checkedCouopn.ticketId,
      custTicketId: this.data.checkedCouopn.id,
      rentType: this.data.orderData.type == 'MONTH' ? 0 : this.data.orderData.type == 'DURATION' ? 1 : 2,
      customerId: wx.getStorageSync('lmtc_customerId')
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            totalPrices: data.data.paidAmount,
            subtract: data.data.discountAmount
          })
        }
      })
  },
  /**
   * 显示优惠券弹窗
   */
  showCouponDialog() {
    if (this.data.couponList.length <= 0) {
      wx.showToast({
        title: '暂无优惠券可用',
        icon: 'none'
      })
      return
    }
    this.setData({
      couponDialog: true
    })
  },
  /**
   * 隐藏优惠券弹窗
   */
  hideCouponDialog() {
    this.setData({
      couponDialog: false
    })
  },
  /**
   * 查询车牌列表
   */
  getCarNumList() {
    let that = this;
    let url = "/customer/car/getCustomerCarList";
    request.http(url, 'GET')
      .then((res) => {
        if (res.data.code == 200) {
          let list = res.data.data;
          if (list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              if (i == 0) {
                list[i].select = true
              } else {
                list[i].select = false
              }
            }
            that.setData({
              carNumList: list
            })
          } else {
            that.setData({
              carNumList: []
            })
          }
        }
      })
  },
  /**
   * 选择车辆
   * @param {*} e 
   */
  checkCar(e) {
    let index = e.currentTarget.dataset.index
    let carNumList = this.data.carNumList
    for (var i = 0; i < carNumList.length; i++) {
      carNumList[i].select = false
      if (index == i) {
        carNumList[i].select = true
      }
    }
    this.setData({
      checkCarIndex: index,
      carNumList: carNumList
    })
  },
  // 显示添加车牌号弹窗
  showAddCarDialog() {
    this.setData({
      addCarDialog: true
    })
  },
  /**
   * 隐藏添加车牌号弹窗
   */
  diddenAddCarDialog() {
    this.setData({
      addCarDialog: false
    })
  },
  /**
   * 输入车牌号
   * @param {*} e 
   */
  onFocus: function (e) {
    var that = this;
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(that.data.carNo)) {
      inputType = 2;
    }
    that.setData({
      showPlateInput: true,
      inputType: inputType,
      activeIptIndex: that.data.carNo.length
    });
  },
  /**
   * 键盘输入操作
   * @param {*} e 
   */
  handlePlateChange(e) {
    let value = e.detail.value;
    let inputLen = this.data.inputLen;
    let type = e.detail.type;
    let carNo = this.data.carNo;
    if (carNo.length < inputLen) {
      carNo += value;
    }
    if (type == 1) {
      this.setData({
        inputType: 2
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
   * 用于点击弹出键盘输入，space为键盘弹出后向上拉取的距离 
   * @param {*} e 
   */
  handleClick(e) {
    /* 150为键盘的高度 */
    let space = -(e.currentTarget.offsetTop - 150);
    /* regExp用于判断当前已输入的车牌号是否是中文，并让键盘显示中文还是英文输入 */
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(this.data.carNo)) {
      inputType = 2;
    }
    this.setData({
      translateSpace: space,
      showPlateInput: true,
      inputType
    })
  },
  /**
   * 键盘隐藏事件
   */
  handleHiddenCarPlate() {
    this.setData({
      showPlateInput: false,
      activeIptIndex: -1
    })
  },
  /**
   * 点击键盘上的确定
   */
  handlePlateConfirm() {
    /* isCarPlate用于判断输入的车牌号是否符合规范 */
    if (!this.isCarPlate(this.data.carNo)) {
      wx.showToast({
        title: '请输入正确车牌号',
        icon: 'none'
      })
      return false;
    }
    this.setData({
      translateSpace: 0,
      showPlateInput: false,
      inputType: 1,
      activeIptIndex: -1
    })
  },
  /**
   * 用于键盘输入删除
   * @param {*} e 
   */
  handlePlateDelete(e) {
    let carNo = this.data.carNo;
    carNo = carNo.substring(0, carNo.length - 1);
    if (carNo.length == 0) {
      this.setData({
        inputType: 1
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
   * 判断车牌号
   * @param {String} value 车牌号
   */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /**
   * 添加车牌号
   */
  addCarNumber() {
    if (addFlag) {
      return
    }
    let that = this;
    let carNo = that.data.carNo;
    if (!that.isCarPlate(that.data.carNo)) {
      wx.showToast({
        title: '请输入正确车牌号',
        icon: 'none'
      })
      return;
    }
    addFlag = true
    let url = '/customer/car/addCustomerCar'
    let params = {
      carNumber: carNo
    }
    request.http(url, 'POST', params)
      .then((res) => {
        let data = res.data
        if (data.code == 200) {
          wx.showToast({
            title: '添加成功'
          })
          that.setData({
            carNo: ''
          })
          that.getCarNumList();
          that.handleHiddenCarPlate()
          that.diddenAddCarDialog()
        } else {
          wx.showToast({
            title: '添加失败，请稍后重试！',
            icon: 'none'
          })
        }
        addFlag = false
      }).catch((errMsg) => {
        addFlag = false
      });
  },
  /**
   * 支付
   */
  payment() {
    let that = this
    let orderData = this.data.orderData
    let carNumList = this.data.carNumList
    let checkCarIndex = this.data.checkCarIndex
    let parkId = this.data.parkId
    let carName = this.data.carName
    let carId = ''
    let url = ''
    let params = {}
    console.log('所有车牌信息：', carNumList)
    for (var i = 0; i < carNumList.length; i++) {
      if (carNumList[i].carNumber == carName) {
        console.log('车牌信息：', carNumList[i])
        carId = carNumList[i].id
        break
      }
    }
    // return
    // if (orderData.type == 'MONTH') {
    url = '/customer/card/buyMonthCard'
    params = {
      carId: carId,
      monthRentType: orderData.monthRentType,
      monthRuleId: orderData.monthRuleId,
      paidAmount: orderData.paidAmount,
      uniformRentType: orderData.uniformRentType,
      parkId: parkId
    }
    // } else if (orderData.type == 'DURATION') {
    //   url = '/customer/card/buyDurationCard'
    //   params = {
    //     durationRuleFeeScaleId: orderData.durationRuleFeeScaleId,
    //     durationRuleId: orderData.durationRuleId,
    //     paidAmount: orderData.paidAmount
    //   }
    // } else if (orderData.type == 'CUSTOMIZE') {
    //   let parkIds = []
    //   for (let i = 0; i < orderData.parkList.length; i++) {
    //     parkIds.push(orderData.parkList[i].id);
    //   }
    //   url = '/customer/card/buyCustomizeCard'
    //   params = {
    //     carId: carNumList[checkCarIndex].id,
    //     parkIdList: parkIds,
    //     paidAmount: orderData.paidAmount,
    //     monthRentType: orderData.monthRentType,
    //   }
    // }
    if (this.data.subtract) {
      params.paidAmount = this.data.totalPrices
      params['ticketId'] = this.data.checkedCouopn.ticketId
      params['custTicketId'] = this.data.checkedCouopn.id
    }
    request.http(url, 'POST', params)
      .then(res => {
        if (res.data.code == 200) {
          if (that.data.subtract && that.data.totalPrices == 0) {
            wx.showToast({
              title: '开通成功，下次停车即可享用服务',
            })
            wx.redirectTo({
              url: '../grade/grade'
            })
          } else {
            let orderCode = res.data.data.orderCode
            //支付
            wx.requestPayment({
              timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
              nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
              package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
              signType: 'MD5', // 签名算法，非必填，（预先约定或者后台传回）
              paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
              success: function (res) { // 成功后的回调函数
                that.getPayState(orderData.type, orderCode)
              },
              fail(res) {
                // wx.showToast({
                //   title: '支付失败',
                //   icon: 'none'
                // })
                console.log(res)
              }
            })
          }
        }
      })
  },
  /**
   * 查询支付状态
   */
  getPayState(cardType, orderCode) {
    let url = '/customer/card/validatePayState'
    let parmas = {
      cardType: cardType,
      orderCode: orderCode
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        if (res.data.code) {
          wx.showToast({
            title: '开通成功，下次停车即可享用服务',
          })
          wx.redirectTo({
            url: '../grade/grade'
          })
        } else {
          wx.showToast({
            title: '开通失败，稍后重试',
            icon: 'none'
          })
        }
      })
  },
  /**
   * 用户协议弹窗
   */
  showAgreement() {
    this.setData({
      agreementShow: true
    })
  },
  /**
   * 关闭用户协议弹窗
   */
  showAgreementClose() {
    this.setData({
      agreementShow: false
    })
  }
})